<?php
/**
 * 访问统计中间件
**/
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class FlowCount
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $ip = $request->getClientIp();
            if($ip!="127.0.0.1"){
                $url = $request->fullUrl();
                $param = json_encode($request->all());
                $province = "未知";
                $city = "未知";
                $area = "未知";
                $ip_url = "https://ip.useragentinfo.com/json?ip=".$ip;
                $result = curl_get($ip_url);
                if($result){
                    $province = isset($result['province'])?$result['province']:$province;
                    $city = isset($result['city'])?$result['city']:$city;
                    $area = isset($result['area'])?$result['area']:$area;
                }
                $created_at = date('Y-m-d H:i:s');
                //保存到访问表中
                DB::table('action_log')->insert([
                    'ip'=>$ip,
                    'url'=>$url,
                    'param'=>$param,
                    'province'=>$province,
                    'city'=>$city,
                    'area'=>$area,
                    'date'=>date('Y-m-d'),
                    'created_at'=>date('Y-m-d H:i:s'),
                ]);


                //当天同个ip访问只记录一次
                $has = DB::table('visit_log')->where('date',date('Y-m-d'))->where('ip',$ip)->first();
                if(!$has){
                    DB::table('visit_log')->insert([
                        'ip'=>$ip,
                        'url'=>$url,
                        'param'=>$param,
                        'province'=>$province,
                        'city'=>$city,
                        'area'=>$area,
                        'date'=>date('Y-m-d'),
                        'created_at'=>$created_at,
                    ]);
                }
            }
        }catch (\Exception $e){

        }
        return $next($request);
    }
}
